package com.mibox.common.utils.location;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.Utils;

import java.lang.ref.WeakReference;

public enum AMapHelper implements AMapLocationListener {
    INSTANCE;

    private AMapLocationClientOption mOption = null;
    private AMapLocationClient mClient = null;
    private WeakReference<AMapCallback> mCallback = new WeakReference<>(null);

    AMapHelper() {
        try {
            PermissionUtils.permission(PermissionConstants.LOCATION, PermissionConstants.PHONE).request();
            AMapLocationClient.updatePrivacyShow(Utils.getApp(), true, true);
            AMapLocationClient.updatePrivacyAgree(Utils.getApp(), true);
            mClient = new AMapLocationClient(Utils.getApp());
            mOption = new AMapLocationClientOption();
            mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            mOption.setOnceLocationLatest(true);
            mClient.setLocationOption(mOption);
            mClient.setLocationListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start() {
        fetch(null, true);
    }

    public void fetch(AMapCallback cb) {
        fetch(cb, false);
    }

    public void fetch(AMapCallback cb, boolean refresh) {
        if (!refresh) {
            AMapLocation loc = mClient.getLastKnownLocation();
            if (loc != null) {
                if (cb != null) {
                    cb.onLocationGet(loc);
                }
                return;
            }
        }
        mCallback = new WeakReference<>(cb);
        mClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mCallback != null) {
            try {
                AMapCallback cb = mCallback.get();
                if (cb != null) {
                    cb.onLocationGet(aMapLocation);
                }
                mClient.stopLocation();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
